/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var threeSum = function (nums) {
  let res = [] //存结果
  nums.sort((a, b) => a - b) //排序
  // nums.length - 2防止下表越界
  // 因为要放下i，start，end三个指针
  for (let i = 0; i < nums.length - 2; i++) {
    if (i == 0 || nums[i] != nums[i - 1]) {
      let start = i + 1
      let end = nums.length - 1
      while (start < end) {
        let result = nums[i] + nums[start] + nums[end] //三数之和
        if (result == 0) {
          res.push([nums[i], nums[start], nums[end]])
          start++
          end--
          // 如果start小于end，同时新start等于旧start
          while (start < end && nums[start] == nums[start - 1]) {
            start++ //往后挪动start
          }
          while (start < end && nums[end] == nums[end + 1]) {
            end-- //往前挪动end
          }
        } else if (result < 0) {
          start++
        } else if (result > 0) {
          end--
        }
      }
    }
  }
  return res
};